package com.fire.eyes.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fire.core.mode.TMitUserToken;
import com.fire.core.service.RedisService;
import com.fire.core.util.DateUtil;
import com.fire.core.util.ToolUtil;
import com.fire.eyes.dao.FireSupervisorMapper;
import com.fire.eyes.dao.FireSupervisorUserMapper;
import com.fire.eyes.model.AssetCategoryModel;
import com.fire.eyes.model.FireSupervisorModel;
import com.fire.eyes.model.FireSupervisorUserModel;
import com.fire.eyes.service.IAssetCategoryService;
import com.fire.eyes.service.IAssetService;
import com.fire.eyes.validation.*;
import com.smartthing.rest.client.SmartThingClient;
import com.smartthing.rest.model.asset.Asset;
import com.smartthing.rest.model.asset.AssetCategory;
import com.smartthing.rest.model.asset.LocationAsset;
import com.smartthing.rest.model.asset.request.AssetCategoryCreateRequest;
import com.smartthing.rest.model.device.Device;
import com.smartthing.rest.model.device.DeviceAssignment;
import com.smartthing.rest.model.device.request.LocationAssetCreatRequest;
import com.smartthing.rest.model.search.AssetSearchResults;
import com.smartthing.rest.model.search.DeviceAssignmentSearchResults;
import com.smartthing.rest.model.search.SearchCriteria;
import com.smartthing.spi.ISmartThingClient;
import com.smartthing.spi.SmartThingException;
import com.smartthing.spi.asset.AssetType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.ws.soap.Addressing;
import java.util.*;

/**
 * @ClassName: AssetServiceImpl
 * @Description: TODO
 * @Author raoyuxing
 * @Date 2019/1/14 18:43
 */
@Service
public class AssetServiceImpl implements IAssetService {

    @Autowired
    private FireSupervisorMapper fireSupervisorMapper;

    @Autowired
    private FireSupervisorUserMapper fireSupervisorUserMapper;

    @Autowired
    private ISmartThingClient client;

    @Autowired
    private IAssetCategoryService categoryService;

    @Autowired
    private RedisService redisService;


    /**
     * 功能描述: 新增资产
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/18 9:58
     */
    @Override
    public LocationAsset addAsset(AddAssetDTO addAssetDTO) throws SmartThingException {

        AssetCategoryModel categoryModel = categoryService.selectById(addAssetDTO.getAssetcategoryid());
        String categroyId = checkCategory(addAssetDTO.getSiteid());
        LocationAssetCreatRequest request = new LocationAssetCreatRequest();
        request.setId(UUID.randomUUID().toString());
        request.setImageUrl(categoryModel.getCategoryurl());
        request.setName(categoryModel.getCategoryname());
        request.setLatitude(0D);
        request.setLongitude(0D);
        request.setElevation(0D);


        String arange ;
        if (categoryModel.getLevel() == 1){
            arange = "outroom";
        }else if (categoryModel.getLevel() == 2){
            arange = "inroom";
        }else if (categoryModel.getLevel() == 3){
            arange = "autospring";
        }else if (categoryModel.getLevel() == 4){
            arange = "gasfire";
        }else if (categoryModel.getLevel() == 5){
            arange = "foamfire";
        }else if (categoryModel.getLevel() == 6){
            arange = "autoalarm";
        }else if (categoryModel.getLevel() == 7){
            arange = "ejectsmoke";
        }else if (categoryModel.getLevel() == 8){
            arange = "smokeprevention";
        }else if (categoryModel.getLevel() == 9){
            arange = "keypart";
        }else {
            arange = "other";
        }

        Map<String,Object> map = new HashMap<>();
        map.put("assetcategoryid",categoryModel.getCategoryid());
        map.put("sitetoken",addAssetDTO.getSiteid());
        map.put("Alocation",addAssetDTO.getLocation());
        map.put("Arange",arange);
        map.put("createtime",DateUtil.getTime(new Date()));
        request.setProperties(map);

        LocationAsset result = client.createLocationAsset(categroyId,request);

        return result;
    }

    /**
     * 功能描述: 获取资产列表
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/18 9:58
     */
    @Override
    public List getAssetList(SiteIdDTO siteIdDTO) throws SmartThingException {

        String categroyId = checkCategory(siteIdDTO.getSiteid());
        SearchCriteria criteria = new SearchCriteria(siteIdDTO.getPage(),siteIdDTO.getPagesize());
        AssetSearchResults results = client.getAssetsByCategoryId(categroyId,criteria);
        List list = new ArrayList();
        for (Asset asset: results.getResults()){
            Map map = new HashMap();
            map.put("assetid",asset.getId());
            map.put("assetname",asset.getName());
            map.put("assetimageurl",asset.getImageUrl());
            map.put("createtime", asset.getProperties().get("createtime"));
            map.put("Alocation",asset.getProperties().get("Alocation"));
            map.put("Arange",asset.getProperties().get("Arange"));
            list.add(map);
        }
        return list;
    }

    /**
     * 功能描述: 查询资产详情
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/18 9:58
     */
    @Override
    public LocationAsset getAssetDetail(AssetIdDTO assetIdDTO) throws SmartThingException {
        String categroyId = checkCategory(assetIdDTO.getSiteid());
        LocationAsset result = client.getLocationAssetDetails(categroyId,assetIdDTO.getAssetid());
        return result;
    }

    /**
     * 功能描述: 我管理的消防单位
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/19 15:48
     */
    @Override
    public List<FireSupervisorModel> getSupervisorListByUser(TokenDTO tokenDTO) {
        TMitUserToken userToken = (TMitUserToken) redisService.get(tokenDTO.getToken());
        FireSupervisorUserModel fireSupervisorUser = new FireSupervisorUserModel();
        fireSupervisorUser.setUserid(Integer.valueOf(userToken.getUserid()));
        FireSupervisorUserModel supervisorUser = fireSupervisorUserMapper.selectOne(fireSupervisorUser);
        String supervisor = supervisorUser.getSupervisor();
        List<FireSupervisorModel> list = fireSupervisorMapper.getSupervisorListById(supervisor);
        return list;
    }

    /**
     * 功能描述: 我管理的消防单位详情
     *
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/19 15:48
     */
    @Override
    public FireSupervisorModel getSupervisor(SuperiorsDTO superiorsDTO) {

        String supervisor = superiorsDTO.getSupervisorid();
        FireSupervisorModel fireSupervisorModel = new FireSupervisorModel();
        fireSupervisorModel.setSupervisorid(supervisor);

        return fireSupervisorMapper.selectOne(fireSupervisorModel);
    }

    /**
     * 功能描述: 根据sitetoken获取资产列表
     *
     * @param siteIdDTO
     * @param:
     * @return:
     * @auther: raoyuxing
     * @date: 2019/1/21 14:20
     */
    @Override
    public List getAssetListBySiteId(SiteIdDTO siteIdDTO) throws SmartThingException {
        SearchCriteria criteria = new SearchCriteria(siteIdDTO.getPage(),siteIdDTO.getPagesize());
        DeviceAssignmentSearchResults results = client.listAssignmentsForSite(siteIdDTO.getSiteid(),null,
                true,true,false,criteria);
        List list = new ArrayList();
        List<DeviceAssignment> assignments = dis(results.getResults());
//        List<DeviceAssignment> assignments = results.getResults();
        for (DeviceAssignment assignment: assignments){
            Map map = new HashMap();
            map.put("assetid",assignment.getAssetId());
            map.put("assetname",assignment.getAssetName());
            map.put("assetimageurl",assignment.getAssetImageUrl());
            map.put("createtime", DateUtil.format(assignment.getCreatedDate()));
            map.put("Alocation",assignment.getMetadata("Alocation"));
            map.put("Arange",assignment.getMetadata("Arange"));
            list.add(map);
        }
        return list;
    }


    public String checkCategory(String siteid) throws SmartThingException{

        String categoryId = "localtion@" + siteid;
        AssetCategory category = client.getCatrgory(categoryId);
        if (ToolUtil.isNotEmpty(category)){
            return category.getId();
        }

        AssetCategoryCreateRequest request = new AssetCategoryCreateRequest();
        request.setId(categoryId);
        request.setName("location@" + System.currentTimeMillis());
        request.setAssetType(AssetType.Location);
        AssetCategory assetCategory = client.creatAssetsCategories(request);
        return assetCategory.getId();
    }

    public List<DeviceAssignment> dis(List<DeviceAssignment> list){
        List<DeviceAssignment> result = new LinkedList<>();
        for (DeviceAssignment assignment : list) {
            boolean b = result.stream().anyMatch(u -> u.getAssetId().equals(assignment.getAssetId()));
            if (!b) {
                result.add(assignment);
            }
        }

        return result;
    }
}
